import {createRouter, createWebHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import menus from './menu'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        // 基础路由
        {
            path:"/",
            redirect:"/dashboard"
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/Login.vue')
        },
        {
            path: '/register',
            name: 'register',
            component: () => import('../views/Register.vue')
        },
        {
            path: '/',
            name: 'layout',
            component: HomeView,
            children: [
                {
                    path: 'dashboard',
                    name: 'Dashboard',
                    component: () => import('../views/Dashboard/Dashboard.vue'),
                    meta: { title: '首页', icon: 'HomeFilled', top: true }
                },
                ...menus
            ]
        },

    ]
})
router.beforeEach((to, from, next) => {
    console.log('路由前置导航守卫==', to, from)
    const token = localStorage.getItem('token')
    
    // 白名单：不需要登录就可以访问的路径
    const whiteList = ['/login', '/register']
    
    if (token) {
        if (to.path === '/login') {
            // 已登录且要跳转的页面是登录页
            next({ path: '/dashboard' })
        } else {
            next()
        }
    } else {
        // 未登录
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单中，直接进入
            next()
        } else {
            next(`/login`) // 否则全部重定向到登录页
        }
    }
})

export default router
